package com.jboost.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jboost.common.api.vo.Result;
import com.jboost.common.constant.CacheConstant;
import com.jboost.common.constant.CommonConstant;
import com.jboost.common.constant.enums.ResultCode;
import com.jboost.common.domain.DomainConstant;
import com.jboost.common.exception.JBoostException;
import com.jboost.common.file.FileCommonVo;
import com.jboost.common.system.api.ISysBaseAPI;
import com.jboost.common.system.util.JwtUtil;
import com.jboost.common.system.vo.LoginUser;
import com.jboost.common.system.vo.SysUserCacheInfo;
import com.jboost.common.system.vo.SysUserSimpleVo;
import com.jboost.common.util.PasswordUtil;
import com.jboost.common.util.RedisUtil;
import com.jboost.common.util.UUIDGenerator;
import com.jboost.common.util.oConvertUtils;
import com.jboost.modules.base.service.BaseCommonService;
import com.jboost.modules.system.constant.SysUserActionEnum;
import com.jboost.modules.system.entity.*;
import com.jboost.modules.system.mapper.*;
import com.jboost.modules.system.model.SysUserSysDepartModel;
import com.jboost.modules.system.service.*;
import com.jboost.modules.system.vo.SysUserDepVo;
import com.jboost.modules.system.vo.SysUserRoleSimpleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @Author: scott
 * @Date: 2018-12-20
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	@Autowired
	private SysUserMapper userMapper;
	@Autowired
	private SysAccountMapper accountMapper;
	@Autowired
	private SysUserAccountMapper userAccountMapper;
	@Autowired
	private SysPermissionMapper sysPermissionMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	@Autowired
	private SysUserDepartMapper sysUserDepartMapper;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private SysDepartMapper sysDepartMapper;
	@Autowired
	private SysRoleMapper sysRoleMapper;
	@Autowired
	private SysDepartRoleUserMapper departRoleUserMapper;
	@Autowired
	private SysDepartRoleMapper sysDepartRoleMapper;
	@Resource
	private BaseCommonService baseCommonService;
	@Autowired
	private ISysRoleService iSysRoleService;

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ISysLogService sysLogService;
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private ISysUserLogService userLogService;

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> resetPassword(String username, String oldpassword, String newpassword, String confirmpassword) {
        SysUser user = userMapper.getUserByNameOrId(username);
        String passwordEncode = PasswordUtil.encrypt(username, oldpassword, user.getSalt());
        if (!user.getPassword().equals(passwordEncode)) {
            return Result.error("旧密码输入错误!");
        }
        if (oConvertUtils.isEmpty(newpassword)) {
            return Result.error("新密码不允许为空!");
        }
        if (!newpassword.equals(confirmpassword)) {
            return Result.error("两次输入密码不一致!");
        }
        String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
        this.userMapper.update(new SysUser().setPassword(password), new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
        return Result.ok("密码重置成功!");
    }

	@Override
	public int resetPassword(String username, String newpassword) {
		SysUser user = userMapper.getUserByNameOrId(username);
		if(null == user.getSalt()){
//			SysAccount account = accountMapper.getAccountByUserId(user.getId());
//			user.setSalt(account.getSalt());
			return 0;
		}
		String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
		return this.userMapper.update(new SysUser().setPassword(password), new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
	}

	@Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> changePassword(SysUser sysUser) {
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        String password = sysUser.getPassword();
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
        sysUser.setPassword(passwordEncode);
        this.userMapper.updateById(sysUser);
        return Result.ok("密码修改成功!");
    }

    @Override
    @CacheEvict(value={CacheConstant.SYS_USERS_CACHE}, allEntries=true)
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteUser(String userId) {
    	SysUser user = this.getById(userId);
		//用户下线
		logout(user);
    	//逻辑删除的用户名和手机唯一处理
		//1.删除用户
		return this.removeById(userId);
	}

	@Override
    @CacheEvict(value={CacheConstant.SYS_USERS_CACHE}, allEntries=true)
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteBatchUsers(String userIds) {
		//1.删除用户
		this.removeByIds(Arrays.asList(userIds.split(",")));
		return false;
	}

	@Override
	public SysUser getUserByName(String username) {
		return userMapper.getUserByName(username);
	}

	@Override
	public SysUser getUserByNameOrId(String key) {
		return userMapper.getUserByNameOrId(key);
	}

	@Override
	public SysUser getDomainUserByName(String username, String domain) {
		return userMapper.getDomainUserByName(username,domain);
	}

	@Override
	public List<SysUser> getUserListByName(String username) {
		return userMapper.getUserListByName(username);
	}

	@Override
	public List<SysUser> getUserByAccountId(String accountId) {
		return userMapper.getUserByAccountId(accountId);
	}

	@Override
	public List<SysUser> getAllUserByAccountId(String accountId) {
		return userMapper.getAllUserByAccountId(accountId);
	}

	@Override
	public List<SysUser> getUserByAccountIds(List<String> accountIds,String domain) {
    	if(CollUtil.isEmpty(accountIds))
    		return new ArrayList<>();
		return userMapper.getUserByAccountIds(accountIds,domain);
	}

	@Override
	@Transactional
	public void addUserWithRole(SysUser user, String roles) {
    	try{
			this.save(user);
		}catch (Exception e){
    		if (e.getMessage().indexOf("index_user_name") > -1){
    			throw new JBoostException("操作失败，用户名不能重复！");
			}
		}
		//用户日志
		userLogService.addBy(user, SysUserActionEnum.NEW,null);
		if(oConvertUtils.isNotEmpty(roles)) {
			String[] arr = roles.split(",");
			for (String roleId : arr) {
				SysUserRole userRole = new SysUserRole(user.getId(), roleId);
				sysUserRoleMapper.insert(userRole);
			}
		}
	}

	@Override
	@CacheEvict(value= {CacheConstant.SYS_USERS_CACHE}, allEntries=true)
	@Transactional
	public void editUserWithRole(SysUser user, String roles) {
		this.updateById(user);
		//先删后加
		sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, user.getId()));
		if(oConvertUtils.isNotEmpty(roles)) {
			String[] arr = roles.split(",");
			for (String roleId : arr) {
				SysUserRole userRole = new SysUserRole(user.getId(), roleId);
				sysUserRoleMapper.insert(userRole);
			}
		}
	}



	@Override
	public List<String> getRole(String username) {
		return sysUserRoleMapper.getRoleByUserName(username);
	}
	@Override
	public List<String> getRoleById(String id) {
		return sysUserRoleMapper.getRoleNameByUserId(id);
	}

	/**
	 * 通过用户名获取用户角色集合
	 * @param username 用户名
     * @return 角色集合
	 */
	@Override
	public Set<String> getUserRolesSet(String username) {
		// 查询用户拥有的角色集合
		List<String> roles = sysUserRoleMapper.getRoleByUserName(username);
		log.info("-------通过数据库读取用户拥有的角色Rules------username： " + username + ",Roles size: " + (roles == null ? 0 : roles.size()));
		return new HashSet<>(roles);
	}

	/**
	 * 通过用户名获取用户权限集合
	 *
	 * @param username 用户名
	 * @return 权限集合
	 */
	@Override
	public Set<String> getUserPermissionsSet(String username) {
		Set<String> permissionSet = new HashSet<>();
		List<SysPermission> permissionList = sysPermissionMapper.queryByUser(username);
		for (SysPermission po : permissionList) {
//			// TODO URL规则有问题？
//			if (oConvertUtils.isNotEmpty(po.getUrl())) {
//				permissionSet.add(po.getUrl());
//			}
			if (oConvertUtils.isNotEmpty(po.getPerms())) {
				permissionSet.add(po.getPerms());
			}
		}
		log.info("-------通过数据库读取用户拥有的权限Perms------username： "+ username+",Perms size: "+ (permissionSet==null?0:permissionSet.size()) );
		return permissionSet;
	}

	@Override
	public SysUserCacheInfo getCacheUser(String username) {
		SysUserCacheInfo info = new SysUserCacheInfo();
		info.setOneDepart(true);
//		SysUser user = userMapper.getUserByName(username);
//		info.setSysUserCode(user.getUsername());
//		info.setSysUserName(user.getRealname());


		LoginUser user = sysBaseAPI.getUserByName(username);
		if(user!=null) {
			info.setSysUserCode(user.getUsername());
			info.setSysUserName(user.getRealname());
			info.setSysOrgCode(user.getOrgCode());
			info.setBusinessId(user.getBusinessId());
		}

		//多部门支持in查询
		List<SysDepart> list = sysDepartMapper.queryUserDeparts(user.getId());
		List<String> sysMultiOrgCode = new ArrayList<String>();
		if(list==null || list.size()==0) {
			//当前用户无部门
			//sysMultiOrgCode.add("0");
		}else if(list.size()==1) {
			sysMultiOrgCode.add(list.get(0).getOrgCode());
		}else {
			info.setOneDepart(false);
			for (SysDepart dpt : list) {
				sysMultiOrgCode.add(dpt.getOrgCode());
			}
		}
		info.setSysMultiOrgCode(sysMultiOrgCode);

		return info;
	}

	// 根据部门Id查询
	@Override
	public IPage<SysUser> getUserByDepId(Page<SysUser> page, String departId,String username) {
		return userMapper.getUserByDepId(page, departId,username);
	}

	@Override
	public IPage<SysUser> getUserByDepIds(Page<SysUser> page, List<String> departIds, String username) {
		return userMapper.getUserByDepIds(page, departIds,username);
	}

	@Override
	public Map<String, String> getDepNamesByUserIds(List<String> userIds) {
		List<SysUserDepVo> list = this.baseMapper.getDepNamesByUserIds(userIds);

		Map<String, String> res = new HashMap<String, String>();
		list.forEach(item -> {
					if (res.get(item.getUserId()) == null) {
						res.put(item.getUserId(), item.getDepartName());
					} else {
						res.put(item.getUserId(), res.get(item.getUserId()) + "," + item.getDepartName());
					}
				}
		);
		return res;
	}

	@Override
	public Map<String, String> getRoleNamesByUserIds(List<String> userIds) {
		List<SysUserRoleSimpleVo> list = this.baseMapper.getRoleNamesByUserIds(userIds);

		Map<String, String> res = new HashMap<String, String>();
		list.forEach(item -> {
			res.put(item.getUserId(), item.getRoleNames());
		});
		return res;
	}

	@Override
	public IPage<SysUser> getUserByDepartIdAndQueryWrapper(Page<SysUser> page, String departId, QueryWrapper<SysUser> queryWrapper) {
		LambdaQueryWrapper<SysUser> lambdaQueryWrapper = queryWrapper.lambda();

		lambdaQueryWrapper.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_0);
        lambdaQueryWrapper.inSql(SysUser::getId, "SELECT user_id FROM sys_user_depart WHERE dep_id = '" + departId + "'");

        return userMapper.selectPage(page, lambdaQueryWrapper);
	}

	@Override
	public IPage<SysUserSysDepartModel> queryUserByOrgCode(String orgCode, SysUser userParams, IPage page) {
		List<SysUserSysDepartModel> list = baseMapper.getUserByOrgCode(page, orgCode, userParams);
		Integer total = baseMapper.getUserByOrgCodeTotal(orgCode, userParams);

		IPage<SysUserSysDepartModel> result = new Page<>(page.getCurrent(), page.getSize(), total);
		result.setRecords(list);

		return result;
	}

	// 根据角色Id查询
	@Override
	public IPage<SysUser> getUserByRoleId(Page<SysUser> page, String roleId, String username) {
		return userMapper.getUserByRoleId(page,roleId,username);
	}


	@Override
	@CacheEvict(value= {CacheConstant.SYS_USERS_CACHE}, key="#username")
	public void updateUserDepart(String username,String orgCode) {
		baseMapper.updateUserDepart(username, orgCode);
	}


	@Override
	public SysUser getUserByPhone(String phone) {
		return userMapper.getUserByPhone(phone);
	}

	@Override
	public SysUser getDomainUserByPhone(String phone, String domain) {
		return userMapper.getDomainUserByPhone(phone);
	}

	@Override
	public SysUser getUserByEmail(String email) {
		return userMapper.getUserByEmail(email);
	}

	@Override
	@Transactional
	public void addUserWithDepart(SysUser user, String selectedParts) {
//		this.save(user);  //保存角色的时候已经添加过一次了
		if(oConvertUtils.isNotEmpty(selectedParts)) {
			String[] arr = selectedParts.split(",");
			for (String deaprtId : arr) {
				SysUserDepart userDeaprt = new SysUserDepart(user.getId(), deaprtId);
				sysUserDepartMapper.insert(userDeaprt);
			}
		}
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value={CacheConstant.SYS_USERS_CACHE}, allEntries=true)
	public void editUserWithDepart(SysUser user, String departs) {
		this.updateById(user);  //更新角色的时候已经更新了一次了，可以再跟新一次
		String[] arr = {};
		if(oConvertUtils.isNotEmpty(departs)){
			arr = departs.split(",");
		}
		//查询已关联部门
		List<SysUserDepart> userDepartList = sysUserDepartMapper.selectList(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, user.getId()));
		if(userDepartList != null && userDepartList.size()>0){
			for(SysUserDepart depart : userDepartList ){
				//修改已关联部门删除部门用户角色关系
				if(!Arrays.asList(arr).contains(depart.getDepId())){
					List<SysDepartRole> sysDepartRoleList = sysDepartRoleMapper.selectList(
							new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId,depart.getDepId()));
					List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
					if(roleIds != null && roleIds.size()>0){
						departRoleUserMapper.delete(new QueryWrapper<SysDepartRoleUser>().lambda().eq(SysDepartRoleUser::getUserId, user.getId())
								.in(SysDepartRoleUser::getDroleId,roleIds));
					}
				}
			}
		}
		//先删后加
		sysUserDepartMapper.delete(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, user.getId()));
		if(oConvertUtils.isNotEmpty(departs)) {
			for (String departId : arr) {
				SysUserDepart userDepart = new SysUserDepart(user.getId(), departId);
				sysUserDepartMapper.insert(userDepart);
			}
		}
	}


	/**
	   * 校验用户是否有效
	 * @param sysUser
	 * @return
	 */
	@Override
	public Result<?> checkUserIsEffective(SysUser sysUser) {
		Result<?> result = new Result<Object>();
		//情况1：根据用户信息查询，该用户不存在
		if (sysUser == null) {
			result.error500("账号名或密码错误");
			baseCommonService.addLog("用户登录失败，用户不存在！", CommonConstant.LOG_TYPE_1, null);
			return result;
		}
		//情况2：根据用户信息查询，该用户已注销
		//update-begin---author:王帅   Date:20200601  for：if条件永远为falsebug------------
		if (CommonConstant.DEL_FLAG_1.equals(sysUser.getDelFlag())) {
		//update-end---author:王帅   Date:20200601  for：if条件永远为falsebug------------
			baseCommonService.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已注销！", CommonConstant.LOG_TYPE_1, null);
			result.error500("账号已注销，请联系管理员处理");
			return result;
		}
		//情况3：根据用户信息查询，该用户已冻结
		if (CommonConstant.USER_FREEZE.equals(sysUser.getStatus())) {
			baseCommonService.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
			result.errorCode(ResultCode.FORBIDDEN.getCode(),"账号已关闭，请联系管理员开通");
			return result;
		}
		return result;
	}
	/**
	   * 校验用户是否有效，用新的错误码
	 * @param sysUser
	 * @return
	 */
	@Override
	public Result<?> checkUserIsEffectiveNew(SysUser sysUser) {
		//情况1：根据用户信息查询，该用户不存在
		if (sysUser == null) {
			baseCommonService.addLog("账号名或密码错误", CommonConstant.LOG_TYPE_1, null);
			return Result.error(ResultCode.USER_NOT_EXIST);
		}
		//情况2：根据用户信息查询，该用户已注销
		//update-begin---author:王帅   Date:20200601  for：if条件永远为falsebug------------
		if (CommonConstant.DEL_FLAG_1.equals(sysUser.getDelFlag())) {
		//update-end---author:王帅   Date:20200601  for：if条件永远为falsebug------------
			baseCommonService.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已注销！", CommonConstant.LOG_TYPE_1, null);
//			result.error500("该用户已注销");
			return Result.error(ResultCode.USER_IS_CANCEL);
		}
		//情况3：根据用户信息查询，该用户已冻结
		if (CommonConstant.USER_FREEZE.equals(sysUser.getStatus())) {
			baseCommonService.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
//			result.error500("该用户已冻结");
			return Result.error(ResultCode.USER_IS_FROZEN);
		}
		JSONObject json = new JSONObject();
		json.put("accountName",sysUser.getUsername());
		return Result.OK(json);
	}

	@Override
	public List<SysUser> queryLogicDeleted() {
		return this.queryLogicDeleted(null);
	}

	@Override
	public List<SysUser> queryLogicDeleted(LambdaQueryWrapper<SysUser> wrapper) {
		if (wrapper == null) {
			wrapper = new LambdaQueryWrapper<>();
		}
		wrapper.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_1);
		return userMapper.selectLogicDeleted(wrapper);
	}

	@Override
	public boolean revertLogicDeleted(List<String> userIds, SysUser updateEntity) {
		String ids = String.format("'%s'", String.join("','", userIds));
		return userMapper.revertLogicDeleted(ids, updateEntity) > 0;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean removeLogicDeleted(List<String> userIds) {
		String ids = String.format("'%s'", String.join("','", userIds));
		// 1. 删除用户
		int line = userMapper.deleteLogicDeleted(ids);
		// 2. 删除用户部门关系
		line += sysUserDepartMapper.delete(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getUserId, userIds));
		//3. 删除用户角色关系
		line += sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, userIds));
		return line != 0;
	}

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateNullPhoneEmail() {
        userMapper.updateNullByEmptyString("email");
        userMapper.updateNullByEmptyString("phone");
        return true;
    }

	@Override
	public void saveThirdUser(SysUser sysUser) {
		//保存用户
		String userid = UUIDGenerator.generate();
		sysUser.setId(userid);
		baseMapper.insert(sysUser);
		//获取第三方角色
		SysRole sysRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleCode, "third_role"));
		//保存用户角色
		SysUserRole userRole = new SysUserRole();
		userRole.setRoleId(sysRole.getId());
		userRole.setUserId(userid);
		sysUserRoleMapper.insert(userRole);
	}

	@Override
	public List<SysUser> queryByDepIds(List<String> departIds, String username) {
		return userMapper.queryByDepIds(departIds,username);
	}

	@Override
	public List<String> getUserIdsByRoleCode(String roleCode) {
		SysRole role = iSysRoleService.lambdaQuery()
				.eq(SysRole::getRoleCode, roleCode)
				.last(" limit 1")
				.one();
		if (role == null) {
			throw new JBoostException("角色不存在");
		}
		return baseMapper.getUserIdsByRoleId(role.getId());
	}

	@Override
	public List<String> getUserIdsByRoleId(String roleId) {
		return baseMapper.getUserIdsByRoleId(roleId);
	}

	@Override
	public JSONObject getBusinessById(String businessId) {
		if (StringUtils.isEmpty(businessId)){
			return null;
		}
		Map<String, Object> result = this.baseMapper.getBusinessById(businessId);
		if(null==result){
			return null;
		}
		return (JSONObject) JSONObject.toJSON(result);
	}

	@Override
	public Result<JSONObject> userInfo(SysUser sysUser, Result<JSONObject> result) {

//		String syspassword = sysUser.getPassword();
//		String username = sysUser.getUsername();
//		// 生成token
//		String token = null;
//		if (StringUtils.isEmpty(sysUser.getToken())) {
//			token = JwtUtil.sign(sysUser.getId(), username, syspassword);
//			// 设置token缓存有效时间
//			redisUtil.set(CommonConstant.PREFIX_USER_ID_TOKEN + sysUser.getId(), token);
//			redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
//			if (sysUser.getLoginType() == 2) {
//				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.WECHAT_EXPIRE_TIME / 1000);
//			} else {
//				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
//			}
//		} else {
//			token = sysUser.getToken();
//			redisUtil.set(CommonConstant.PREFIX_USER_ID_TOKEN + sysUser.getId(), token);
//		}
//		JSONObject obj = new JSONObject();
//		//头像
//		if( !StringUtils.isEmpty(sysUser.getAvatar()) ){
//			sysUser.setAvatarFile( sysBaseAPI.getFileById(sysUser.getAvatar()) );
//		}
//		//店铺信息
//		if(DomainConstant.BUSINESS.getCode().equals(sysUser.getDomain()) && !CommonConstant.DEFAULT_STORE_TENANT.equals(sysUser.getId())){
//			JSONObject business = sysBaseAPI.getBusinessById(sysUser.getId());
//			if(null!=business){
//				String storeId = business.getString("id");
//				String storeStatus = business.getString("status");
//				redisUtil.set(storeId+"_status",storeStatus);
//			}
//			obj.put("business",business);
//
//		}
//		//当前用户首页
//		List<SysPermission> permissionList = sysPermissionMapper.queryByUser(sysUser.getId());
//		if(CollUtil.isNotEmpty(permissionList)){
//			sysUser.setIndex(permissionList.stream().filter(p->p.isRoute()&&!"layouts/RouteView".equals(p.getComponent()) ).findFirst().get());
//		}

		// 获取用户部门信息
//		List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
//		obj.put("departs", departs);
//		if (departs == null || departs.size() == 0) {
//			obj.put("multi_depart", 0);
//		} else if (departs.size() == 1) {
//			this.updateUserDepart(username, departs.get(0).getOrgCode());
//			obj.put("multi_depart", 1);
//		} else {
//			//查询当前是否有登录部门
//			// update-begin--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
//			SysUser sysUserById = this.getById(sysUser.getId());
//			if (oConvertUtils.isEmpty(sysUserById.getOrgCode())) {
//				this.updateUserDepart(username, departs.get(0).getOrgCode());
//			}
//			// update-end--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
//			obj.put("multi_depart", 2);
//		}
		//角色名称
//		List<String> roles = this.getRoleById(sysUser.getId());
//		sysUser.setRoleNameList(roles);
//		//pc最后登录时间
//		SysLog pcSysLog = sysLogService.getOne(new QueryWrapper<SysLog>().lambda().eq(SysLog::getLogType, CommonConstant.LOG_TYPE_1).eq(SysLog::getOperateType, CommonConstant.LOG_OPERATE_TYPE_PC).eq(SysLog::getUserid, sysUser.getId()).orderByDesc(SysLog::getCreateTime).last(" limit 1"));
//		if (null != pcSysLog)
//			sysUser.setPcLastLoginTime(pcSysLog.getCreateTime());
//		//wx最后登录时间
//		SysLog wxSysLog = sysLogService.getOne(new QueryWrapper<SysLog>().lambda().eq(SysLog::getLogType, CommonConstant.LOG_TYPE_1).eq(SysLog::getOperateType, CommonConstant.LOG_OPERATE_TYPE_WX).eq(SysLog::getUserid, sysUser.getId()).orderByDesc(SysLog::getCreateTime).last(" limit 1"));
//		if (null != wxSysLog)
//			sysUser.setWxLastLoginTime(wxSysLog.getCreateTime());
//		obj.put("token", token);
//		baseCommonService.addLog("%%%%%%%%%%", CommonConstant.LOG_TYPE_1, sysUser.getLoginType() == 2 ? CommonConstant.LOG_OPERATE_TYPE_WX : CommonConstant.LOG_OPERATE_TYPE_PC);
//		obj.put("userInfo", sysUser);
////		obj.put("sysAllDictItems", sysDictService.queryAllDictItems());
//		result.setResult(obj);
		result.success("登录成功");
		return result;
	}

	/**
	 *
	 * @param businessId
	 * @param userId
	 * @param num 只能是1，多的话还要修改
	 */
	@Override
	@Transactional
	public void businessUseAccountNum(String businessId,String userId, int num) {
		if(num!=1){
			throw new JBoostException("机构消耗的账号数量无效："+num);
		}
		//机构账号使用数量
		JSONObject business = sysBaseAPI.getBusinessById(businessId);
		if (null == business){
			throw new JBoostException("机构不存在！");
		}
		Integer accountTotal = business.getInteger("account_total");
		Integer accountUsed = business.getInteger("account_used");
		if (accountUsed >= accountTotal){
			throw new JBoostException("操作失败，机构账号额度不够！");
		}

		this.baseMapper.businessSubtractAccountNum(businessId,num);
		//获取机构购买账号数量的订单
		//todo num > 1
		Map<String, Object> result = this.baseMapper.getBusinessAccountNumValidOrder(businessId);
		if(null != result){
			JSONObject accountOrder = (JSONObject)JSONObject.toJSON(result);
			//从订单扣除数量，退换时要用
			String orderId = accountOrder.getString("order_id");
			this.baseMapper.businessOrderSubtractAccountNum(orderId,num);
			//使用记录
			this.baseMapper.addAccountNumLog(userId,businessId,orderId,num);
		}
	}

	@Override
	public void businessFreedAccountNum(String businessId, String userId) {

		//找出使用记录，再找出哪个订单扣除的
		Map<String, Object> result = this.baseMapper.getBusinessAccountNumOrderLog(businessId,userId);
		Integer num = 1;
		if(null!=result){
			JSONObject accountOrderLog = (JSONObject)JSONObject.toJSON(result);
			String orderId = accountOrderLog.getString("account_num_id");
			num = accountOrderLog.getInteger("num");
			//退回到当时扣除的订单里
			if(null!=orderId && num >0){
				this.baseMapper.businessOrderAddAccountNum(orderId,num);
			}
		}
		//机构账号总数量回退
		this.baseMapper.businessAddAccountNum(businessId,num);

	}

	@Override
	public void logout(SysUser sysUser) {

		log.info(" 用户名:  " + sysUser.getRealname() + ",退出成功！ ");
		//清空用户登录Token缓存
		String token = (String) redisUtil.get(CommonConstant.PREFIX_USER_ID_TOKEN + sysUser.getId());
		redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
		//清空用户登录Shiro权限缓存
		redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
		//清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
		redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
	}

	@Override
	public List<SysUserSimpleVo> listSimpleUserByIds(List<String> userIds) {
		List<SysUser> userList = this.lambdaQuery().in(SysUser::getId,userIds).list();
		if (CollUtil.isEmpty(userList)){
			return new ArrayList<>();
		}
		List<String> avatarIds = userList.stream().map(SysUser::getAvatar).collect(Collectors.toList());
		List<FileCommonVo> avatarList = sysBaseAPI.listFiles(avatarIds);
		return userList.stream().map(user->{
			SysUserSimpleVo vo = new SysUserSimpleVo();
			vo.setId(user.getId());
			vo.setUsername(user.getUsername());
			vo.setRealname(user.getRealname());
			vo.setPhone(user.getPhone());
			FileCommonVo avatarFile = avatarList.stream().filter(avatar->avatar.getFileId().equals(user.getAvatar())).findFirst().orElse(null);
			if(null!=avatarFile){
				vo.setIconFile(avatarFile);
			}
			return vo;
		}).collect(Collectors.toList());
	}
}
